import path from 'node:path';
import fse from 'fs-extra';
import { defineEventHandler, readBody } from 'h3';
import { TEMP_DIR } from '../utils/constants';

export default defineEventHandler(async (event) => {
  const { filename, fileHash } = await readBody(event);
  const ext = filename.split('.')[1];

  const filePath = path.resolve(TEMP_DIR, `${fileHash}.${ext}`);

  const res: any = { errno: 0, msg: `文件 ${filename} 上传成功` };

  if (fse.existsSync(filePath)) {
    res.shouldUpload = false;
  } else {
    res.shouldUpload = true;
  }

  res.uploadedList = await getUploadedList(filename);

  return res;
});

async function getUploadedList(filename: string) {
  return fse.existsSync(path.resolve(TEMP_DIR, `chunkDir_${filename}`))
    ? await fse.readdirSync(path.resolve(TEMP_DIR, `chunkDir_${filename}`))
    : [];
}
